package com.dinree.activity;

import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;

import com.base.library.BaseActivity;
import com.dinree.R;
import com.dinree.api.UserApi;
import com.dinree.databinding.ActivityLoginBinding;
import com.jakewharton.rxbinding2.view.RxView;
import com.tencent.smtt.sdk.CookieManager;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;

import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.base.library.Constant.WINDOW_DURATION;

public class LoginActivity extends BaseActivity {
    private String phone;
    private String pwd;
    private ActivityLoginBinding activityLoginBinding;

    @Override
    public int getLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        phone = getIntent().getStringExtra("phone");
        activityLoginBinding = getViewDataBinding();
        RxView.clicks(activityLoginBinding.tvRegister).throttleFirst(WINDOW_DURATION, TimeUnit.SECONDS).subscribe(v -> {
            Intent intent = new Intent(mContext, RegisterActivity.class);
            startActivity(intent);
        });
        RxView.clicks(activityLoginBinding.tvForget).throttleFirst(WINDOW_DURATION, TimeUnit.SECONDS).subscribe(v -> {
            Intent intent = new Intent(mContext, ForgetPwdActivity.class);
            startActivity(intent);
        });
        RxView.clicks(activityLoginBinding.btnLogin).throttleFirst(WINDOW_DURATION, TimeUnit.SECONDS).subscribe(v -> {
            login();
        });
        RxView.clicks(activityLoginBinding.btnBack).throttleFirst(WINDOW_DURATION, TimeUnit.SECONDS).subscribe(v -> {
            Intent intent = new Intent(mContext, MainActivity.class);
            startActivity(intent);
            finish();
        });
        RxView.clicks(activityLoginBinding.wx).throttleFirst(WINDOW_DURATION, TimeUnit.SECONDS).subscribe(v -> {
            UMShareAPI.get(mContext).getPlatformInfo(LoginActivity.this, SHARE_MEDIA.WEIXIN, authListener);
        });
        RxView.clicks(activityLoginBinding.qq).throttleFirst(WINDOW_DURATION, TimeUnit.SECONDS).subscribe(v -> {
            UMShareAPI.get(mContext).getPlatformInfo(LoginActivity.this, SHARE_MEDIA.QQ, authListener);
        });
        RxView.clicks(activityLoginBinding.wb).throttleFirst(WINDOW_DURATION, TimeUnit.SECONDS).subscribe(v -> {
            UMShareAPI.get(mContext).getPlatformInfo(LoginActivity.this, SHARE_MEDIA.SINA, authListener);
        });
    }

    UMAuthListener authListener = new UMAuthListener() {
        /**s
         * @desc 授权开始的回调
         * @param platform 平台名称
         */
        @Override
        public void onStart(SHARE_MEDIA platform) {

        }

        /**
         * @desc 授权成功的回调
         * @param platform 平台名称
         * @param action 行为序号，开发者用不上
         * @param data 用户资料返回
         */
        @Override
        public void onComplete(SHARE_MEDIA platform, int action, Map<String, String> data) {
            UMShareAPI.get(mContext).getPlatformInfo(LoginActivity.this, platform, getUserInfoListener);
        }

        /**
         * @desc 授权失败的回调
         * @param platform 平台名称
         * @param action 行为序号，开发者用不上
         * @param t 错误原因
         */
        @Override
        public void onError(SHARE_MEDIA platform, int action, Throwable t) {
            Toast.makeText(mContext, "登陆失败：" + t.getMessage(), Toast.LENGTH_LONG).show();
        }

        /**
         * @desc 授权取消的回调
         * @param platform 平台名称
         * @param action 行为序号，开发者用不上
         */
        @Override
        public void onCancel(SHARE_MEDIA platform, int action) {
        }
    };

    UMAuthListener getUserInfoListener = new UMAuthListener() {
        @Override
        public void onCancel(SHARE_MEDIA arg0, int arg1) {
        }

        @Override
        public void onStart(SHARE_MEDIA share_media) {

        }

        @Override
        public void onComplete(SHARE_MEDIA platform, int action, final Map<String, String> data) {
            if (data != null) {
                String thirdId = data.get("uid");
                String thirdName = data.get("name");
                String thirdGender = data.get("gender");
                String thirdType = "";
                String thirdPic = data.get("iconurl");
                if (platform == SHARE_MEDIA.QQ) {
                    thirdType = "QQ";
                } else if (platform == SHARE_MEDIA.WEIXIN) {
                    thirdType = "WX";
                } else if (platform == SHARE_MEDIA.SINA) {
                    thirdType = "WB";
                }
                UserApi.getInstance(mContext).third_login(thirdName, thirdId, thirdGender, thirdPic).subscribe(user -> {
                    if (user != null) {
                        CookieManager cookieManager = CookieManager.getInstance();
                        cookieManager.setCookie("user_info", "think:{\"user_id\":\"" + user.user_id + "\",\"user_token\":\"" + user.user_token + "\"}");
                        realm.insertOrUpdate(user);
                        UserApi.getInstance(mContext).updateRetrofit(mContext.getApplicationContext());//更新拦截器里面的Token
                        Intent intent = new Intent(mContext, MainActivity.class);
                        startActivity(intent);
                        finish();
                    } else {
                        showMsg("登录失败");
                    }
                }, e -> {
                    e.printStackTrace();
                    showMsg(e.getMessage());
                });
            }
        }

        @Override
        public void onError(SHARE_MEDIA arg0, int arg1, Throwable arg2) {
            showMsg(arg2.getMessage());
        }
    };

    @Override
    public void onBackPressed() {
        Intent intent = new Intent(mContext, MainActivity.class);
        startActivity(intent);
        finish();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }

    private void login() {
        phone = activityLoginBinding.editPhone.getText().toString().trim();
        pwd = activityLoginBinding.editPwd.getText().toString().trim();
        UserApi.getInstance(mContext).login(phone, pwd).subscribe(user -> {
            if (user != null) {
                CookieManager cookieManager = CookieManager.getInstance();
                cookieManager.setCookie("user_info", "think:{\"user_id\":\"" + user.user_id + "\",\"user_token\":\"" + user.user_token + "\"}");
                realm.insertOrUpdate(user);
                UserApi.getInstance(mContext).updateRetrofit(mContext.getApplicationContext());//更新拦截器里面的Token
                Intent intent = new Intent(mContext, MainActivity.class);
                startActivity(intent);
                finish();
            } else {
                showMsg("登录失败");
            }
        }, e -> {
            e.printStackTrace();
            showMsg(e.getMessage());
        });
    }
}

